//
//  BeeGroupController.m
//  FbeeAPP
//
//  Created by dev-m on 2018/3/7.
//  Copyright © 2018年 mohao. All rights reserved.
//

#import "BeeGroupController.h"
#import "BeeGroupHeaderView.h"
#import "UIButton+BCYImage.h"
#import "FbeeCommitBtn.h"
#import "BeeGroupTopicCell.h"
#import "BeeGroupListObj.h"
#import "TopicObj.h"
#import "UIScrollView+BCYRefresh.h"


@interface BeeGroupController ()<UITableViewDelegate,UITableViewDataSource>
{
    BeeGroupListObj *beeObj;
    NSMutableArray *listArray;
    
    UIView *navBar;
    BeeGroupHeaderView *header;
    UITableView *mainTable;
    
    //加入按钮
    FbeeCommitBtn *joinBtn;
    //发表
    UIButton *sendBtn;
    UIImageView *shadow;
    
    NSUInteger pageNum;
    BOOL isEnd;
    BOOL isDetail;
}

@end

@implementation BeeGroupController

-(void)dealloc
{
    NSLog(@"BeeGroupController dealloc");
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(instancetype)initWithObj:(BeeGroupListObj *)obj
{
    self = [super init];
    
    if (self) {
        beeObj = obj;
    }
    
    return self;
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.titleLabel.text = beeObj.groupName;
    
    listArray = [[NSMutableArray alloc] init];
    pageNum = 1;
    
    //加入圈子成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(joinSuccess) name:Notification_JoinBeeGroupSuccess object:nil];
    //退出圈子成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(quitSuccess) name:Notification_QuitBeeGroupSuccess object:nil];
    //写话题成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:Notification_WriteTopicSuccess object:nil];
    //评论成功
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reLoadMainTable) name:Notification_TopicCommentSuccess object:nil];
    //分享
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toShare) name:Notification_Share object:nil];
    
    
    self.largeTitle.hidden = YES;

    [self buildView];
    
    [self getListData];
    [LoadingHelper showLoadingOnView:self.view];
    
    //静默获取圈子详情信息
    [self getBeeDetailData];


}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)buildView
{
    navBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, NavBarHeight)];
    [self.view addSubview:navBar];
    
    UIButton *backNav =  [UIButton makeButton:^(TTButtonExtend *make) {
        make.setFrame(CGRectMake(0, StatusHeight, 60, 44));
        make.addImage([UIImage imageNamed:@"nav_back_w"],UIControlStateNormal);
        make.addTarget(self,@selector(navback));
        make.imageEdgeInsets = UIEdgeInsetsMake(13.5, 16, 13.5, 27);
        make.tag = 666;
        [navBar addSubview:make];
    }];
    
    UIButton *menu =  [UIButton makeButton:^(TTButtonExtend *make) {
        make.setFrame(CGRectMake(IPHONEWIDTH-44, StatusHeight, 44, 44));
        make.addImage([UIImage imageNamed:@"nav_menu_w"],UIControlStateNormal);
        make.addTarget(self,@selector(toMore));
        [make setImageCenter];
        [navBar addSubview:make];
    }];
    
    UIButton *menu2 =  [UIButton makeButton:^(TTButtonExtend *make) {
        make.setFrame(CGRectMake(IPHONEWIDTH-44, StatusHeight, 44, 44));
        make.addImage([UIImage imageNamed:@"nav_menu_b"],UIControlStateNormal);
        make.addTarget(self,@selector(toMore));
        [make setImageCenter];
        [self.navigationView addSubview:make];
    }];
    
    header = [[BeeGroupHeaderView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, 170*UISCALE) obj:beeObj];
    [self.view addSubview:header];
    mainTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, IPHONEWIDTH, IPHONEHEIGHT) style:UITableViewStylePlain];
    mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    mainTable.alwaysBounceVertical = YES;
    mainTable.backgroundColor = [UIColor clearColor];
    mainTable.delegate = self;
    mainTable.dataSource = self;
    [mainTable setContentInset:UIEdgeInsetsMake(header.bottom, 0, 0, 0)];
    [self.view addSubview:mainTable];
    
    __weak BeeGroupController *sel = self;
    [mainTable addHeaderByRefreshHandler:^{
        [sel refreshData];

    }];
    
    [mainTable addFooterByRefreshHandler:^{
        [sel loadMore];
    }];
    
    [self.view bringSubviewToFront:header];
    [self bringTitleToFront];
    [self.view bringSubviewToFront:navBar];
    
    [self getActionBtn];
    
}

-(void)joinSuccess
{
    beeObj.isJoin = YES;
    
    for(TopicObj *obj in listArray)
    {
        obj.isJoin = beeObj.isJoin;
    }
    
    [self getActionBtn];
}

-(void)quitSuccess
{
    beeObj.isJoin = NO;
    
    for(TopicObj *obj in listArray)
    {
        obj.isJoin = beeObj.isJoin;
    }
    
    [self getActionBtn];
}


-(void)getActionBtn
{
    [sendBtn removeFromSuperview];
    [joinBtn removeFromSuperview];
    [shadow removeFromSuperview];
    sendBtn = nil;
    shadow = nil;
    joinBtn = nil;
    
    if (beeObj.isJoin) {
        shadow = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 108, 108)];
        shadow.image = [UIImage imageNamed:@"beegroup_send_shadow"];
        [self.view addSubview:shadow];
        
        sendBtn = [UIButton makeButton:^(TTButtonExtend *make) {
            make.setFrame(CGRectMake(0, 0, 60, 60));
            make.addImage([UIImage imageNamed:@"beegroup_send"],UIControlStateNormal);
            make.bottom = IPHONEHEIGHT - 35;
            make.right = IPHONEWIDTH - 30;
            make.addTarget(self,@selector(sendAction));
            [self.view addSubview:make];
        }];
        
        shadow.centerX = sendBtn.centerX;
        shadow.centerY = sendBtn.centerY + 20;
    }
    else
    {
        @weakify(self)
        joinBtn = [[FbeeCommitBtn alloc] initWithTitle:@"+加入"];
        joinBtn.centerX = self.view.centerX;
        joinBtn.bottom = IPHONEHEIGHT - IPhoneXDel;
        [joinBtn onClick:^{
            @strongify(self)
            [self joinAction];
        }];
        [self.view addSubview:joinBtn];
    }
}

#pragma mark - action

-(void)sendAction
{
    [[JumpManager sharedManager] jumpToTopicWrite:beeObj.groupId];
}

-(void)joinAction
{
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_JoinBeeGroup object:beeObj.groupId];
}

-(void)toMore
{
    if (![UserInfoManager sharedManager].isLogin) {
        
        [[JumpManager sharedManager] jumpToLogin];
        
        return;
    }
    
    if (!beeObj.isJoin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:Notification_JoinBeeGroup object:beeObj.groupId];
        return;
    }
    
    [[JumpManager sharedManager] jumpToBeeGroupMore:beeObj];
}

-(void)toShare
{
    [[JumpManager sharedManager] jumpToShare:beeObj];
}

#pragma - mark scrollView

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ((scrollView.contentOffset.y + header.height) > 0) {
        header.top = -(scrollView.contentOffset.y + header.height);
    }
    else
    {
        header.top = 0;
    }
    
    if (scrollView.contentSize.height > scrollView.height - header.height) {
        float alphaY = scrollView.contentOffset.y + header.height;
        float alpha = alphaY / (scrollView.bounds.size.height/5.0f);
        alpha = alpha<0?0:alpha;
        alpha = alpha>1?1:alpha;
        [self.navigationView setAlpha:alpha];
        [self.view bringSubviewToFront:self.navigationView];
    }

}

#pragma mark - TableView Cell

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return listArray.count;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TopicObj *obj = [listArray objectAtIndex:indexPath.row];
    
    return obj.height;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellId = @"CELLID";
    
    TopicObj *obj = [listArray objectAtIndex:indexPath.row];
    
    BeeGroupTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    
    if (!cell) {
        cell = [[BeeGroupTopicCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    cell.dataObj = obj;
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    TopicObj *obj = [listArray objectAtIndex:indexPath.row];
    [[JumpManager sharedManager] jumpToTopicDetail:obj];
}

-(void)reLoadMainTable
{
    [mainTable reloadData];
}

#pragma mark - request

-(void)refreshData
{
    if ([LoadingHelper isLoadingFromView:self.view]) {
        
        [mainTable endRefreshing];
        
        return;
    }
    
    pageNum = 1;
    isEnd = NO;
    [self getListData];
}

-(void)loadMore
{
    if ([LoadingHelper isLoadingFromView:self.view]) {
        
        [mainTable endRefreshing];
        
        return;
    }
    
    [self getListData];
}

-(void)getListData
{
    NSString *url = [NSString stringWithFormat:@"%@?gid=%@&pageNo=%@&pageSize=10",BeeGroupTopicList_URL,beeObj.groupId,@(pageNum)];
    
    [self get:url code:BeeGroupTopicList_URL_Code];
}


-(void)getBeeDetailData
{
    //获取详情
    NSString *url = [NSString stringWithFormat:@"%@/%@?uid=%@",BeeGroupDetail_URL,beeObj.groupId,[UserInfoManager sharedManager].userId];
    [self get:url code:BeeGroupDetail_URL_Code];
    
    //获取邀请码
    [self post:ShareInviteCode_URL param:@{@"gid":beeObj.groupId,@"uid":[UserInfoManager sharedManager].userId} code:ShareInviteCode_URL_Code];
    
}

#pragma mark - response

-(void)requestSuccess:(id)data code:(NSInteger)code
{
    //重置Bee圈信息
    if (code == BeeGroupDetail_URL_Code) {
        [beeObj setObjByData:SafeGetDictionaryValue([data objectForKey:@"beeGroup"])];
        isDetail = YES;
    }
    
    if (code == ShareInviteCode_URL_Code) {
        beeObj.inviteCode = SafeGetStringValue([data objectForKey:@"invitation"]);
        beeObj.joinSeq = SafeGetStringValue([data objectForKey:@"joinSeq"]);
    }
    
    if (code == BeeGroupTopicList_URL_Code) {
        
        [LoadingHelper removeLoadingOnView:self.view];
        
        [mainTable endRefreshing];
        
        [EmptyViewHelper removeEmptyFromView:mainTable];
        
        if (pageNum == 1) {
            [listArray removeAllObjects];
        }
        
        NSArray *dataArray = [data objectForKey:@"topicList"];
        
        if (dataArray.count == 0) {
            
            if (listArray.count == 0) {
                UIView *emptyView = [EmptyViewHelper showEmptyOnView:mainTable imageName:@"common_empty" text:NSLocalizedString(@"textEmptyBeeGroup", nil)];
                emptyView.height = mainTable.height - header.height - 35;
                emptyView.top = 0;
            }
            
            isEnd = YES;
        }
        else
        {
            pageNum++;
        }
        
        for (NSDictionary *dataDict in dataArray)
        {
            TopicObj *obj = [[TopicObj alloc] init];
            [obj setObjByDict:dataDict];
            obj.isJoin = beeObj.isJoin;
            [listArray addObject:obj];
        }
        
        [mainTable reloadData];
        
    }
    
    
}

-(void)requestLogicError:(id)data code:(NSInteger)code
{
    if (code == BeeGroupTopicList_URL_Code) {
        [LoadingHelper removeLoadingOnView:self.view];
        [mainTable endRefreshing];
    }
    
}

-(void)requestFailure:(NSError *)error code:(NSInteger)code
{
    if (code == BeeGroupTopicList_URL_Code) {
        [LoadingHelper removeLoadingOnView:self.view];
        [mainTable endRefreshing];
    }
}


@end
